#include <QApplication>
#include <QIcon>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSharedMemory>
#include <QTextCodec>
#include "global/SysConstants.h"
#include "helper/SettingsHelper.h"
#include "helper/FileHelper.h"
#include "helper/ConfigHelper.h"
#include "helper/AuthManager.h"
#include "service/UserService.h"
#include "service/OrgService.h"

int main(int argc, char* argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    static QSharedMemory* singleApp = new QSharedMemory("ExpertApp");
    if(!singleApp->create(1))
    {
        qApp->quit();
        return -1;
    }

#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
    qputenv("QT_QUICK_CONTROLS_STYLE", "Basic");
#else
    qputenv("QT_QUICK_CONTROLS_STYLE", "Default");
#endif
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QApplication::setApplicationName("expertin");
    QApplication::setApplicationDisplayName(SysConstants::getInstance()->displayName());
    QApplication::setQuitOnLastWindowClosed(false);
    qmlRegisterSingletonType<SysConstants>(
        "GlobalConsts", 1, 0, "SysConstants",
        [](QQmlEngine* engine, QJSEngine* scriptEngine) -> QObject*
    {
        Q_UNUSED(engine)
        Q_UNUSED(scriptEngine)
        return SysConstants::getInstance();
    }
    );

    // 注册文件操作类
    qmlRegisterSingletonType<FileHelper>("FileHelper", 1, 0, "FileHelper",
                                         [](QQmlEngine* engine, QJSEngine* scriptEngine) -> QObject*
    {
        Q_UNUSED(engine)
        Q_UNUSED(scriptEngine)
        return FileHelper::getInstance();
    }
                                        );

    QApplication app(argc, argv);
    ConfigHelper::instance().initialize();
    SettingsHelper::getInstance()->init(argv);

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("SettingsHelper", SettingsHelper::getInstance());

    //注册用户元类型
    // qRegisterMetaType<UserInfo>("UserInfo");
    //注册QML类型
    qmlRegisterSingletonInstance("Admin.Auth", 1, 0, "AuthManager", AuthManager::getInstance());
    //注册业务类
    UserService userService;
    engine.rootContext()->setContextProperty("userService", & userService);

    OrgService orgService;
    engine.rootContext()->setContextProperty("orgService", & orgService);

    const QUrl url(QStringLiteral("qrc:/qml/App.qml"));
    QObject::connect(
        & engine, & QQmlApplicationEngine::objectCreated, & app,
        [url](QObject* obj, const QUrl& objUrl)
    {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    },
    Qt::QueuedConnection);
    engine.load(url);
    return app.exec();
}
